package sqlOp

import (
	"fmt"
	"strings"
)

const Equal = "="
const NotEqual = "!="
const Like = "like"
const NotLike = "not like"
const IN = "in"
const NotIN = "not in"
const LessThan = "<"
const GreatThan = ">"
const LessThanOrEqual = "<="
const GreatThanOrEqual = ">="
const DESC = "desc"
const ASC = "asc"
const Where = "where"

func DimLeft(s string) string {
	return "%" + s
}
func DimRight(s string) string {
	return s + "%"
}
func DimAll(s string) string {
	return "%" + s + "%"
}
func AndEqual(column string) string {
	return fmt.Sprintf("and %s %s ?\n", column, Equal)
}
func AndNoEqual(column string) string {
	return fmt.Sprintf("and %s %s ?\n", column, NotEqual)
}
func AndLike(column string) string {
	return fmt.Sprintf("and %s %s ?\n", column, Like)
}
func AndNoLike(column string) string {
	return fmt.Sprintf("and %s %s ?\n", column, NotLike)
}
func AndIn(column string) string {
	return fmt.Sprintf("and %s %s ?\n", column, IN)
}
func AndNoNotIn(column string) string {
	return fmt.Sprintf("and %s %s ?\n", column, NotIN)
}
func AndLessThan(column string) string {
	return fmt.Sprintf("and %s %s ?\n", column, LessThan)
}
func AndGreatThan(column string) string {
	return fmt.Sprintf("and %s %s ?\n", column, GreatThan)
}
func AndLessThanOrEqual(column string) string {
	return fmt.Sprintf("and %s %s ?\n", column, LessThanOrEqual)
}
func AndGreatThanOrEqual(column string) string {
	return fmt.Sprintf("and %s %s ?\n", column, GreatThanOrEqual)
}
func Group(column ...string) string {
	return fmt.Sprintf("group by %s\n", strings.Join(column, ","))
}
func SumColumn(column string) string {
	return fmt.Sprintf("sum(IFNULL(%s,0)) as %s", column, column)
}
func CountColumn(column ...string) string {
	if column != nil {
		return fmt.Sprintf("count(%s) as count", strings.Join(column, ","))
	} else {
		return "count(1) as count"
	}
}
func SelectColumn(tableName string, column ...string) string {
	columns := strings.Join(column, ",\n")
	return fmt.Sprintf("select\n%s\nfrom %s\n", columns, tableName)
}
func SelectCount(childSql string, column ...string) string {
	columns := strings.Join(column, ",\n")
	return fmt.Sprintf("select\n%s\nfrom (\n%s\n) _tmp_\n", columns, childSql)
}

type OrderByModel struct {
	Column    string
	OrderType string
}

func OrderBy(orderByColumns ...OrderByModel) string {
	if orderByColumns != nil && len(orderByColumns) > 0 {
		rd := "order by "
		for _, o := range orderByColumns {
			rd += fmt.Sprintf("%s %s,", o.Column, o.OrderType)
		}
		rd = rd[:len(rd)-1] + "\n"
		return rd
	}
	return ""
}
